/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package io.netty.example.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

/**
 * Echoes back any received data from a client.
 */
public final class EchoServer {
    //这两都是启动从启动配置中获取 ssl:1 port:8022
    static final boolean SSL = System.getProperty("ssl") != null;
    static final int PORT = Integer.parseInt(System.getProperty("port", "8008"));

    public static void main(String[] args) throws Exception {
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {//开启SSl
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }

        // Configure the server.
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);//连接事件处理组（线程组）-创建的都是Nio线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup();//读写等事件处理组（线程组）
        final EchoServerHandler serverHandler = new EchoServerHandler();//事件处理器
        try {
            ServerBootstrap b = new ServerBootstrap();//服务端启动引导工具类
            b.group(bossGroup, workerGroup)//设置accept(连接处理)工作组和I/O(读写)工作组
                    .channel(NioServerSocketChannel.class)//channel：事件模型与网络套接字或具有I/O能力的组件的连接  读、写、连接、绑定等操作。 也就是说最重要功能,选择哪个事件处理器select poll epoll Kqueue  NioServerSocketChannel:自动识别事件模型
                    .option(ChannelOption.SO_BACKLOG, 100)//option：传输的性质相关属性  hannelOption.SO_BACKLOG：求处理线程全满时，用于临时存放已完成三次握手的请求的队列的最大长度。
                    .handler(new LoggingHandler(LogLevel.INFO))//日志等级
                    .childHandler(new ChannelInitializer<SocketChannel>() {//Boss负责处理连接，Worker(child)负责处理读写，childHandler决定了worker(child)能干哪些事
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();//在pipeline添加的处理器根据类型是事件到达时会被调用处理
                            if (sslCtx != null) {
                                p.addLast(sslCtx.newHandler(ch.alloc()));
                            }
//                            p.addLast(new StringDecoder());
//                            p.addLast(new StringEncoder());
                            //p.addLast(new LoggingHandler(LogLevel.INFO));
                            p.addLast(serverHandler);
                        }
                    });

            // 1.绑定端口号 2.同步启动
            ChannelFuture f = b.bind(PORT).sync();

            // 同步等待服务关闭
            f.channel().closeFuture().sync();
        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
